﻿using Puppy.Scheduler.Common;
using Puppy.Scheduler.Tasks;
using System;
using System.Collections.Generic;
using System.Text.Json;

namespace Puppy.Scheduler.Models
{
    [Serializable]
    public class ProcessorMapTaskRequest
    {
        public long InstanceId { get; set; }

        public long SubInstanceId { get; set; }

        public string TaskName { get; set; }

        public List<SubTask> SubTasks { get; set; }

        public ProcessorMapTaskRequest(TaskEntity parentTask, List<object> subTaskList, string taskName)
        {
            InstanceId = parentTask.InstanceId;
            SubInstanceId = parentTask.SubInstanceId;
            TaskName = taskName;
            SubTasks = new List<SubTask>();
            foreach (var subTask in subTaskList)
            {
                // 同一个 Task 内部可能多次 Map，因此还是要确保线程级别的唯一
                var subTaskId = parentTask.TaskId + "." + ThreadLocalStore.GetTaskIdLocal().Increment();
                SubTasks.Add(new SubTask
                {
                    TaskId = subTaskId,
                    TaskContent = JsonSerializer.SerializeToUtf8Bytes(subTask)
                });
            }
        }

        public class SubTask
        {
            public string TaskId { get; set; }

            public byte[] TaskContent { get; set; }
        }
    }
}
